﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ProcrastinationKit.Connectivity;
using ProcrastinationKit.Connectivity.Configuration;
using EnvDTE80;
using VSAddins;
using EnvDTE;
using System.Diagnostics;

namespace PKTwitter
{
    public class PKTwitter : IPKPluggable
    {
        private PKSettings _settings;
        private DTE2 _dte;
        private Twitter.Twitter _twitter;
        private static PKTwitter _PKTwitter;

        #region IPKPluggable Members

        //For better results -and handling-, this thing is Singleton, and should have be here -in memory- ALWAYS!!!!
        public static IPKPluggable GetInstance()
        {
            if (_PKTwitter == null)
                _PKTwitter = new PKTwitter();
            return _PKTwitter;
        }

        private PKTwitter() { }

        public void Initialize(ProcrastinationKit.Connectivity.Configuration.PKSettings settings, EnvDTE80.DTE2 dte)
        {
            _settings = settings;
            _dte = dte;
            _twitter = Twitter.Twitter.GetInstance();
            _twitter.OnTweetPosted += new EventHandler<Twitter.TwitterEventArgs>(_twitter_OnTweetPosted);
            _twitter.OnGetTweets += new EventHandler<Twitter.TwitterEventArgs>(_twitter_OnGetTweets);

            //todo: remove
             #if (DEBUG)
            //_twitter.Login("pk4vs", "procrastination");
            //_dte.ItemOperations.NewFile("General\\Visual C# Class", "test.cs", "");
            #endif


        }

        public void OnMessageReceived(object sender, PKMessageEventArgs e)
        {
            if (e.Token != "twitter") return;
            
            try
            {
                switch (e.Command)
                {
                    case "gettweets":
                        SetTextInTheStatusBar("Obtaining tweets...");
                        _twitter.GetTweetsAsync();
                        break;
                    case "tweet":
                    default:
                        SetTextInTheStatusBar("Posting tweet...");
                        _twitter.PostTweetAsync(e.Arguments.Trim());
                        break;
                }
                
            }
            catch(Exception ex)
            {
                SetTextInTheStatusBar(ex.Message);
            }
        }

        void _twitter_OnTweetPosted(object sender, Twitter.TwitterEventArgs e)
        {
            if (e.ex == null)
            {
                SetTextInTheStatusBar("Tweet posted! :)");

            }
            else
            {
                SetTextInTheStatusBar("Sorry, we can't post your tweet :(");
            }
        }

        void _twitter_OnGetTweets(object sender, Twitter.TwitterEventArgs e)
        {
            if (e.ex == null)
            {
                //
                Document doc = null;
                foreach (Document document in _dte.Documents)
                {
                    if (document.ActiveWindow.Caption.Equals("tweets.html"))
                    {
                        doc = document;
                        break;
                    }
                }
                if (doc == null)
                {
                    Window w = _dte.ItemOperations.NewFile("General\\HTML Page", "tweets.html", "");
                    doc = w.Document;
                    
                }

                HTMLWindow objHTMLWin = doc.ActiveWindow.Object as HTMLWindow;
                vsHTMLTabs Tab = objHTMLWin.CurrentTab;

                // Switch to the "source" tab.
                objHTMLWin.CurrentTab = vsHTMLTabs.vsHTMLTabsSource;


                // Get an EditPoint at the start of the text.
                TextWindow textDoc = objHTMLWin.CurrentTabObject as TextWindow;
                TextSelection textSelection = textDoc.ActivePane.Selection;

                TextRanges textRanges = textSelection.TextRanges;
                EditPoint ep = null;
                EditPoint ep2 = null;
                EditPoint epTMP = null;

                ep = textDoc.ActivePane.StartPoint.CreateEditPoint();
                if (ep.FindPattern("<body>", (int)vsFindOptions.vsFindOptionsFromStart, ref epTMP, ref  textRanges))
                {
                    

                    // Look for the end of the document body.
                    if (ep.FindPattern("</body>", (int)vsFindOptions.vsFindOptionsNone, ref ep2, ref textRanges))
                    {
                        textSelection.MoveToPoint(epTMP, false);
                        textSelection.MoveToPoint(ep2, true);
                        Debug.WriteLine(textSelection.Text);
                        //textSelection.WordLeft(true, 2);
                        
                        textSelection.Text = String.Empty;
                        
                        foreach (Twitter.Tweet tweet in e.Tweets)
                        {
                            epTMP.Insert(string.Format("<div>{3}<span style='color:Navy;'>{0}</span>  <span>{1}</span><br/>{3}<span style='color:Gray;'>{2}</span>{3}</div>{3}", tweet.User == null ? "" : tweet.User.ScreenName, tweet.Text, tweet.DateCreated, Environment.NewLine));
                        }
                        textSelection.Insert("</body>", (int)vsInsertFlags.vsInsertFlagsInsertAtEnd);


                    }
                }
                SetTextInTheStatusBar(String.Format("{0} Tweets obtained! :)", e.Tweets.Count));
                objHTMLWin.CurrentTab = vsHTMLTabs.vsHTMLTabsDesign;
                
                doc.Activate();
                textSelection.StartOfDocument(true);

            }
            else
            {
                SetTextInTheStatusBar("Sorry, we can't obtain the tweets :(");
            }
        }

        public List<VSAddins.CommandInfo> CommandsToAdd
        {
            get 
            {
                return FillCommands();
            }
        }

        public event ProcrastinationKit.Connectivity.SaveConfigurationHandler OnSaveConfiguration;

        #endregion

        private List<VSAddins.CommandInfo> FillCommands()
        {
            List<VSAddins.CommandInfo> lst = new List<VSAddins.CommandInfo>();

            CommandInfo command;

            command = new CommandInfo("Login", new ActionNoArg(ShowLogin))
            {
                OnToolBar = true,
                ToolTip = "Login to Twitter",
            };
            lst.Add(command);
            
            return lst;
        }

        private void ShowLogin()
        {
            frmLogin frm = new frmLogin();
            frm.ShowDialog();
        }

        public void SetTextInTheStatusBar(string text)
        {
            _dte.StatusBar.Text = text;
        }
    }
}
